YAHOO.namespace('ext.Graph');
/**
 * @class YAHOO.ext.Graph.LineGraph
 * @extends YAHOO.ext.util.Observable
 * Simple Vector Line Graph class
 * @cfg {Object} graphData array of array object 
 * Example: [[{x:0,y:5},{x:1,y:10}],[{x:0,y:8},{x:1,y:13}]]
 * @constructor
 * Create a new line
 * @param {Object} config The config object
 */
YAHOO.ext.Graph.LineGraph = function(renderTo,config){
	YAHOO.ext.util.Config.apply(this,config);
	this.colors = ['blue', 'green', 'grey', 'red'];
    if(renderTo){
        this.render(renderTo);
    }
}
YAHOO.extendX(YAHOO.ext.Graph.LineGraph, YAHOO.ext.util.Observable, {
    render : function(renderTo){
        this.graphTemplate = new YAHOO.ext.DomHelper.Template('<div></div>');
		this.container = getEl(renderTo);
		this.width = this.container.getWidth();
		this.height = this.container.getHeight();
		this.el = this.graphTemplate.append(this.container.dom, [''], true);
		this.el.addClass('graph-main');
		this.el.setHeight(this.height);
		this.el.setWidth(this.width);
		this.mainX = 25;
		this.mainY = this.height -25;
		this.lengthY = this.height - this.mainY;
		this.lengthX = this.width - this.mainX;
		var x = this.getMaxX(this.graphData);
		var y = this.getMaxY(this.graphData);
		var lines = [];
		var colorIndex = 0;
		var vm = YAHOO.ext.Vector.VectorManager;
		this.scaleX = parseFloat(x/(this.lengthX-this.mainX));
		this.scaleY = parseFloat(y/(this.mainY-this.lengthY));
		this.rescaleData();
		this.adjustData();
		this.group = YAHOO.ext.Vector.VectorManager.getGroup(this.el, 
			{
				height: this.height,
				width: this.width
			});
		this.graphBox = YAHOO.ext.Vector.VectorManager.getBox(this.group.getEl(), 
			{
				strokecolor: 'green',
				strokeweight: '2',
				height: this.height,
				width: this.width
			});
		this.legendGroup = YAHOO.ext.Vector.VectorManager.getGroup(this.group.getEl(),
			{
				height: 60,
				width: 120,
				left: (this.width - 125),
				top: 5
			});
		this.legend = YAHOO.ext.Vector.VectorManager.getRoundBox(this.legendGroup.getEl(),
    		{
    			strokecolor: 'gray',
				height: 60,
				width: 120
    		}
    	);
		this.xAxis = YAHOO.ext.Vector.VectorManager.getLine(this.group.getEl(),
			{
			id: 'xLine',
			strokecolor: 'steelblue',
			strokeweight: '1px',
			fromx:this.mainX,
			fromy:this.mainY,
			tox:this.lengthX,
			toy:this.mainY
			});		
		this.yAxis = YAHOO.ext.Vector.VectorManager.getLine(this.group.getEl(),
			{
			id: 'yLine',
			strokecolor: 'steelblue',
			strokeweight: '1px',
			fromx:this.mainX,
			fromy:this.mainY,
			tox:this.mainX,
			toy:this.lengthY
    		});
    	
    	for(var i=0; i<this.graphData.length; i++) {
    		lines[i] = YAHOO.ext.Vector.VectorManager.getPoly(this.group.getEl(),
    		{
    			strokecolor: this.colors[i],
    			strokeweight: '1',
    			pts: this.graphData[i]
    		});
    	}
    	vm.getLine(this.legendGroup.getEl(),{strokecolor:lines[0].strokecolor,fromx:75,fromy:20,tox:115,toy:20});
    	vm.getLine(this.legendGroup.getEl(),{strokecolor:lines[1].strokecolor,fromx:75,fromy:45,tox:115,toy:45});
    	vm.getBox(this.legendGroup.getEl(),{cls:'graph-legend',strokecolor:'none',text:'series 1',height:'25px',width:'60px',left:2,top:2,shadow:'false'});
    	vm.getBox(this.legendGroup.getEl(),{cls:'graph-legend',strokecolor:'none',text:'series 2',height:'25px',width:'60px',left:2,top:34,shadow:'false'});
    },
    rescaleData : function(){
    	for(var i=0; i<this.graphData.length; i++) {
    		for(var j=0; j<this.graphData[i].length; j++) {
    			this.graphData[i][j].x = this.graphData[i][j].x / this.scaleX;
    			this.graphData[i][j].y = this.graphData[i][j].y / this.scaleY;    			
    		}
    	}
    },
    adjustData : function(){
    	for(var i=0; i<this.graphData.length; i++) {
    		for(var j=0; j<this.graphData.length; j++) {
    			this.graphData[i][j].x = this.graphData[i][j].x + this.mainX;
    			this.graphData[i][j].y = this.mainY - this.graphData[i][j].y;    			
    		}
    	}
    },
    getMaxX : function(obj){
    	var m = 0;
	    	for(var i=0; i<obj.length; i++) {
	    		for(var j=0; j<obj[i].length; j++) {
		    		(m<obj[i][j].x)?m=obj[i][j].x:'';	
	    		}
    	}
    	this.maxX = m;
    	return m;
    },
    getMaxY : function(obj){
    	var m = 0;
	    	for(var i=0; i<obj.length; i++) {
	    		for(var j=0; j<obj[i].length; j++) {
		    		(m<obj[i][j].y)?m=obj[i][j].y:'';	
	    		}
	    	}
    	this.maxY = m;
    	return m;
    },
    /**
     * Returns the line element
     * @return {YAHOO.ext.Element}
     */
    getEl : function(){
        return this.el;  
    }
});

/*
    object with:
    id-> id of the element (div) to
    be used to create the chart.
    width(optional)->width of the chart.
    height(optional)->height of the chart
    idLegend(optional)-> id of the element where legend will be rendered
*/
YAHOO.ext.Graph.Barchart=function(config){
    
        this.id=config.id;
        this.el=getEl(config.id);
        this.el.addClass("Barchart");
        this.width=500;
        this.height=500;
        this.legendHeight=100,
        this.legendWidth=100
        YAHOO.ext.util.Config.apply(this,config);
}
YAHOO.ext.Graph.Barchart.prototype={
    /*
        Add an item to the chart
        @item {object) with :
        value - The value (in percent) of the bar to render
        label (optional)- The label of the element (for a legend)
        color(optional)- The color of the bar , if empty a random color is generated 
    */
    addItem:function(item){
        if(this.items==null){
            this.items=[];
        }
        this.items.push(item);

    },
   
    /*
        renders the chart 
        id--optional to render a legend to the element of the id
    */
    render:function(){

         if(this.items==null){
            if(this.isServer){
                 this.CallServer();
            }
            return;
         }
         /*
            GraphBox
            
         */
        var vm = YAHOO.ext.Vector.VectorManager;
       
        this.group = vm.getGroup(this.el,
             {
                height: this.height,
                width: this.width
             });
        this.graphBox = vm.getBox(this.group.getEl(),
         {
            strokecolor: 'gray',
            height: this.height,
            width: this.width
         });
         
         var lastTop=10;
        
         for(var i=0;i< this.items.length;i++){
            if(i!=0)
                lastTop+=i+40;
                vm.getBox(this.group.getEl(),
                    {
                        strokecolor:this.randomBg(this.items[i]),
                        height:'20px',
                        width:this.width*this.items[i].value/100+"px",
                        left:20,
                        top:lastTop,
                        shadow:'true',
                        fillcolor:this.items[i].color
                       
                     }
              );
            
              vm.getBox(this.group.getEl(),
                {
                 cls:'graph-legend',
                 strokecolor:'white',
                 text:this.items[i].value+"%",
                 height:'25px',
                 width:'60px',
                 left: (this.width -130),
                 top:lastTop,
                 shadow:'false'
                }
               );
            
         }
        
         
          this.renderLegend();
        
        
         
    },

    /*
        Gets a random Background color for each bar
    */
    randomBg:function(item) {
        if(item.color){
            return item.color;
        }
        var hex1=new Array("0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D", "E", "F")
        var hex2=new Array("0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D", "E", "F")
        var hex3=new Array("0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D", "E", "F")
        var hex4=new Array("0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D", "E", "F")
        var hex5=new Array("0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D", "E", "F")
        var hex6=new Array("0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D", "E", "F")
        var bg="#"+hex1[Math.floor(Math.random()*hex1.length)]+hex2[Math.floor(Math.random()*hex2.length)]+hex3[Math.floor(Math.random()*hex3.length)]+hex4[Math.floor(Math.random()*hex4.length)]+hex5[Math.floor(Math.random()*hex5.length)]+hex6[Math.floor(Math.random()*hex6.length)]
        item.color=bg;
        return bg;
    },
    /*
        Tels the chart that the data will be server-side loaded
        and what page to call to get the data
    */
    setDataSource:function(sUrl){
       this.Url=sUrl;
       this.isServer=true;
       
    } ,
    /*
        private ->Calls the server-side page 
        to get the data
    */
    CallServer:function(){
        var callback =
        {
          success: this.HandleSuccess,
          failure: function(o) {alert("Error "+o.responseText);},
          scope:this
        }
        var transaction = YAHOO.util.Connect.asyncRequest('POST', this.Url, callback, "foo=bar");
    },
    HandleSuccess:function(resp){
        
        this.items=eval(resp.responseText);
        this.render();
        
    },
    /*
        Renders the chart legend
    */
    renderLegend:function(){
         var vm = YAHOO.ext.Vector.VectorManager;
         
         this.legendGroup = vm.getGroup(this.group.getEl(),
         {
            height: this.legendHeight,
            width: this.legendWidth,
            left: (this.width + 50),
            top: 5
         }
         );
        
         this.legend = vm.getRoundBox(this.legendGroup.getEl(),
          {
            strokecolor: 'gray',
            height: this.legendHeight,
            width: this.legendWidth
          
          }
         );
         var dist=32;//distance between legends
         var distLine=32;//distance between lines
         var iniL=30;
         var iniB=17;
         for(var i=0;i< this.items.length;i++){
            vm.getLine(this.legendGroup.getEl(),{strokecolor:this.items[i].color,fromx:20,fromy:iniL,tox:35,toy:iniL,strokeweight: '5px'});
            vm.getBox(this.legendGroup.getEl(),{cls:'graph-legend',strokecolor:'white',text:this.items[i].label,height:'25px',width:'160px',left:40,top:iniB,shadow:'false'});
            iniL+=distLine;
            iniB+=dist;
         }
        
    }  
}